package com.shelpe.services.tenant.item;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import com.shelpe.services.tenant.mongomodel.SimbadTask;


@Component("taskProcessor")
public class TaskProcessor implements ItemProcessor<SimbadTask,SimbadTask>{

	private static final Logger logger = LoggerFactory.getLogger(TaskProcessor.class);
	
	@Autowired
    private LoadBalancerClient loadBalancer;
	
	
	@Override
	public SimbadTask process(SimbadTask item) throws Exception {
		// TODO Auto-generated method stub
		if(shouldSchedule(item)){
			ServiceInstance instance = loadBalancer.choose(item.getServiceId());
			String url = String.format("http://%s:%s", instance.getHost(), instance.getPort());
			url += item.getTaskId();
			
			get(url);
			
			item.setLastTime(new Date());
		}else{
			logger.info(">>>>>>>>>>>TaskProcessor should not been scheduled");
		}
		
		return item;
	}
	
	private boolean shouldSchedule(SimbadTask task){
		
		Date lastTime = task.getLastTime();
		Long freq = task.getFreq();
		Date now = new Date();
		Calendar calendar = Calendar.getInstance(); 
		calendar.setTime(lastTime);
		calendar.add(Calendar.SECOND, freq.intValue());
		
		return calendar.getTime().getTime() <= now.getTime();
	}
	
	private void get(String url) {  
		
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            // 创建httpget.    
            HttpGet httpget = new HttpGet(url);  
            logger.info("executing request {}", httpget.getURI());  
            // 执行get请求.    
            CloseableHttpResponse response = httpclient.execute(httpget);  
            try {  
                // 获取响应实体    
                HttpEntity entity = response.getEntity();  
                logger.info("--------------------------------------");  
                // 打印响应状态    
                logger.info("StatusLine: {}", response.getStatusLine());  
                if (entity != null) {  
                    // 打印响应内容长度    
                	logger.info("Response content length: {}", entity.getContentLength());                             
                }  
                logger.info("------------------------------------");  
            } finally {  
                response.close();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            // 关闭连接,释放资源    
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
	
}
